package com.srwl.mytx.adapter;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.google.android.material.snackbar.Snackbar;
import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.LocationMapActivity;
import com.srwl.mytx.activity.LoginActivity;
import com.srwl.mytx.activity.TopicDetailsActivity;
import com.srwl.mytx.activity.UserProfileActivity;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Contact;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.fragment.GaoDeMapFragment;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.Utils;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SearchResultAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int ITEM_TYPE_NORMAL = 0;
    private static final int ITEM_TYPE_FIND_NOTHING = 1;
    private List<Topic> searchResultList;
    private Context context;
    private SearchResultItemClickListener itemClickListener;
    private Fragment fragment;

    public SearchResultAdapter(Context context, Fragment fragment, List<Topic> searchHistoryList) {
        this.searchResultList = searchHistoryList;
        this.fragment = fragment;
        this.context = context;
    }

    @Override
    public int getItemViewType(int position) {
        if (0 == searchResultList.size()) {
            return ITEM_TYPE_FIND_NOTHING;
        } else if (searchResultList.get(position).getType() != null && searchResultList.get(position).getType() == Constant.TOPIC_TYPE_USER_INFO) {
            return Constant.TOPIC_TYPE_USER_INFO;
        } else {
            return ITEM_TYPE_NORMAL;
        }

    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == ITEM_TYPE_NORMAL) {
            View view = LayoutInflater.from(context).inflate(R.layout.search_result_item_layout, parent, false);
            return new MyViewHolder(view);
        } else if (viewType == Constant.TOPIC_TYPE_USER_INFO) {
            View view = LayoutInflater.from(context).inflate(R.layout.search_result_item_user_layout, parent, false);
            return new UserInfoHolder(view);
        } else {
            View view = LayoutInflater.from(context).inflate(R.layout.search_result_find_nothing_item_layout, parent, false);
            return new MyViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, final int position) {
        if (searchResultList.size() != 0) {
            final Topic topic = searchResultList.get(position);
            if (viewHolder instanceof MyViewHolder) {
                MyViewHolder holder = (MyViewHolder) viewHolder;
                holder.tv_title.setText(topic.getTitle());
                holder.tv_address.setText(topic.getAddress());
                if (topic.getType() != null) {

                    switch (topic.getType()) {
                        case Constant.TOPIC_TYPE_LOST_PEOPLE:
                            holder.iv_topicType.setImageResource(R.drawable.tx_topic_type_lost_person);
                            break;
                        case Constant.TOPIC_TYPE_REWARD:
                            holder.iv_topicType.setImageResource(R.drawable.tx_topic_type_lost_person);
                            break;
                        case Constant.TOPIC_TYPE_EXPOSE:
                            holder.iv_topicType.setImageResource(R.drawable.tx_topic_type_expose);
                            break;
                        case Constant.TOPIC_TYPE_GIFT:
                            holder.iv_topicType.setImageResource(R.drawable.tx_topic_type_gift);
                            break;
                        case Constant.TOPIC_TYPE_SHOW:
                            holder.iv_topicType.setImageResource(R.drawable.tx_topic_type_show);
                            break;
                        case Constant.TOPIC_TYPE_AUCTION:
                            holder.iv_topicType.setImageResource(R.drawable.tx_topic_type_auction);
                            break;
                        case Constant.TOPIC_TYPE_GOODS:
                            holder.iv_topicType.setImageResource(R.drawable.tx_topic_type_goods);
                            break;
                        case Constant.TOPIC_TYPE_AREA:
                            holder.iv_topicType.setImageResource(R.drawable.tx_topic_type_area);
                            break;
                        case Constant.TOPIC_TYPE_INDUSTRY:
                            holder.iv_topicType.setImageResource(R.drawable.tx_topic_type_industry);
                            break;
                        case Constant.TOPIC_TYPE_SCHOOL:
                            holder.iv_topicType.setImageResource(R.drawable.tx_topic_type_school);
                            break;

                    }
                }
                holder.iv_location.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        if (itemClickListener != null) {
//                            itemClickListener.onItemClick(position, searchResult);
//                        }

                        context.startActivity(new Intent(context, LocationMapActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, topic));
                    }
                });
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        fragment.startActivityForResult(new Intent(context, TopicDetailsActivity.class).putExtra(Constant.EXTRA_INFO_TOPIC, searchResultList.get(position)), GaoDeMapFragment.REQUEST_CODE_TO_TOPIC_DETAIL);
                    }
                });


            } else if (viewHolder instanceof UserInfoHolder) {
                final UserInfoHolder holder = (UserInfoHolder) viewHolder;
                final User user = topic.getManager();
                holder.tv_username.setText(user.getUsername());
               // Glide.with(context).load(user.getAvatar()).diskCacheStrategy(DiskCacheStrategy.ALL).error(R.drawable.tx_default_avatar).into(holder.iv_avatar);
                GlideLoadUtils.glideLoad(context,user.getAvatar(),holder.iv_avatar,R.drawable.tx_default_avatar_1);
                holder.iv_avatar.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        context.startActivity(new Intent(context, UserProfileActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, user));
                    }
                });
                holder.tv_username.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        context.startActivity(new Intent(context, UserProfileActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, user));
                    }
                });
                holder.btn_addContact.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (Utils.isTempUser(UserProfileManager.getInstance().getLoginUserInfo())) {
                            context.startActivity(new Intent(context, LoginActivity.class).putExtra("EXTRA_CONTENT", "添加联系人需要先登录"));
                            return;
                        }
                        //String phoneNumber = UserProfileManager.getInstance().getUserPhoneNumber();
//                        if (TextUtils.isEmpty(phoneNumber)) {
//                            ConfirmDialog confirmDialog = new ConfirmDialog(context, "提示", "绑定手机号才可以添加好友，去绑定？", true);
//                            confirmDialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
//                                @Override
//                                public void confirm() {
//                                    context.startActivity(new Intent(context, UpdateUserInfoActivity.class));
//                                }
//                            });
//                            confirmDialog.show();
//                        } else {
//                            if (itemClickListener != null) {
//                                itemClickListener.onAddContact(user, holder.et_reason.getText().toString());
//                            }
//                        }
                        Contact contact=new Contact();
                        if (holder.cb_location.isChecked()) {
                            contact.setTLocation("1");
                        } else {
                            contact.setTLocation("0");
                        }
                        holder.sendInviteMessage(contact,user.getuId(),holder.et_reason.getText().toString());
                    }
                });

            }
        }


    }

    @Override
    public int getItemCount() {
        if (searchResultList.size() == 0) {
            return 1;
        } else {
            return searchResultList.size();
        }

    }

    class MyViewHolder extends RecyclerView.ViewHolder {


        TextView tv_title;
        TextView tv_address;
        ImageView iv_location;
        ImageView iv_topicType;

        private MyViewHolder(View itemView) {
            super(itemView);
            tv_title = itemView.findViewById(R.id.tv_title);
            tv_address = itemView.findViewById(R.id.tv_address);
            iv_location = itemView.findViewById(R.id.iv_location);
            iv_topicType = itemView.findViewById(R.id.iv_topic_type);
        }
    }

    class UserInfoHolder extends RecyclerView.ViewHolder {
        private static final String TAG = "UserInfoHolder";
        ImageView iv_avatar;
        TextView tv_username;
        EditText et_reason;
        Button btn_addContact;
        CheckBox cb_location;

        public UserInfoHolder(@NonNull View itemView) {
            super(itemView);
            iv_avatar = itemView.findViewById(R.id.iv_avatar);
            tv_username = itemView.findViewById(R.id.tv_username);
            et_reason = itemView.findViewById(R.id.et_reason);
            btn_addContact = itemView.findViewById(R.id.btn_add_contact);
            cb_location=itemView.findViewById(R.id.cb_location);
        }

        public void sendInviteMessage(Contact contact, String targetUserId, String inviteMessage) {
//            ProgressDialog progressDialog = new ProgressDialog(context);
//        progressDialog.setContent(getResources().getString(R.string.Is_sending_a_request));
//        progressDialog.setCanceledOnTouchOutside(false);
//        progressDialog.show();

            if (TextUtils.isEmpty(inviteMessage)) {
                inviteMessage = itemView.getResources().getString(R.string.default_invite_message);
            }
            contact.setInviteMessage(inviteMessage);
            contact.settId(targetUserId);


            JSONObject body = new JSONObject();
            body.put("token", UserProfileManager.getInstance().getLoginUserInfo().getToken());
            body.put("ct", contact);
            RetrofitManager.getInstance()
                    .createRequest(UserService.class)
                    .sendInviteMessage(body)
                    .enqueue(new Callback<CommonResult>() {
                        @Override
                        public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                            // progressDialog.dismiss();
                            CommonResult result = response.body();
                            if (!response.isSuccessful() || result == null) {
                                Log.e(TAG, "onResponse: " + response.message());
                                showToast(context.getString(R.string.system_busy));
                                return;
                            }
                            if (result.isError()) {
                                switch (result.getStatus()) {

                                    case Constant.REFUSE_ADD_CONTACT:
                                        showToast("对方已经拒绝您的添加联系人请求," + result.getData().toString() + "天后可再次添加");
                                        break;
                                    case Constant.REFUSE_ADD_CONTACT_IS_HAVE:
                                        showToast("好友请求已经发起了,不能重新发起好友请求");
                                        break;
                                    default:
                                        showToast("系統错误");
                                }
                                return;
                            }


                            if (result.getData() != null) {
                                JSONObject jsonObject = (JSONObject) result.getData();
                                Contact contact = jsonObject.toJavaObject(Contact.class);
                                //前端使用tid进行关联查询,所以将后端的mid设置给tid
                                //  contact.setmId(UserProfileManager.getInstance().getLoginUserInfo().getuId());
                                contact.settId(contact.getUser().getuId());
                                contact.setGroupName(contact.getGroupName());
                                DBManager.getInstance().getDaoSession().getContactDao().insertOrReplace(contact);
                                Helper.getInstance().refreshCache();
                                LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(context);
                                broadcastManager.sendBroadcast(new Intent(Constant.ACTION_CONTACT_CHANGED));
                                showToast("你一直在对方的联系人中，添加联系人完成");
                            } else {
                                showToast(context.getString(R.string.send_invite_message_seccess));

                            }
                        }

                        @Override
                        public void onFailure(Call<CommonResult> call, Throwable t) {
                            //  progressDialog.dismiss();
                            showToast(context.getString(R.string.system_busy));
                        }
                    });
        }

        public void showToast(String content){
            Snackbar.make(itemView,content,Snackbar.LENGTH_LONG);
        }
    }

    public void setSearchResultItemClickListener(SearchResultItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    public interface SearchResultItemClickListener {
        void onItemClick(int position, Topic topic);

        void onAddContact(User userInfo, String reason);
    }

}
